/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package employ;

import database.Database;
import database.User;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import user.SearchListPopulate;

/**
 *
 * @author Jack
 */
public class MainFrame extends javax.swing.JFrame implements ActionListener {

    ArrayList<User> listOfUsers;

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }

    /**
     * Creates new form MainFrame
     */
    public MainFrame() {
        initComponents();
        btnSearch.addActionListener(this);
        btnEdit.addActionListener(this);
        btnSave.addActionListener(this);
        btnDeleteUser.addActionListener(this);
        btnAddUser.addActionListener(this);

        //when list item is clicked this is called
        userList.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 1) {
                    int selectedItem = userList.getSelectedIndex();
                    userInfoPanel.setUser(listOfUsers.get(selectedItem));
                    btnEdit.setEnabled(true);
                    btnSave.setEnabled(false);
                }
            }
        });

        btnSave.setEnabled(false);

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == btnSearch) {
            refreshSearchList();
        }
        if (e.getSource() == btnEdit) {
            userInfoPanel.editUser();
            btnSave.setEnabled(true);
            btnEdit.setEnabled(false);
        }
        if (e.getSource() == btnSave) {
            userInfoPanel.saveUser();
            btnEdit.setEnabled(true);
            btnSave.setEnabled(false);
        }
        if (e.getSource() == btnDeleteUser) {
            userInfoPanel.clearAllFields();
            Database.connect();
            Database.removeUser(userInfoPanel.getUserId());
            Database.shutdown();

            listOfUsers.remove(userList.getSelectedIndex());
            userList.setModel(new SearchListPopulate(listOfUsers));
        }
        if (e.getSource() == btnAddUser) {
            new NewUserForm(listOfUsers).setVisible(true);
        }
    }

    private void refreshSearchList() {
        listOfUsers = null;
        Database.connect();

        //get search selection (Name,Address or Phone) and query database
        int selectedItem = cbSelection.getSelectedIndex();
        if (selectedItem == 0) {
            listOfUsers = Database.getUsersByName(tfSearch.getText());
        } else if (selectedItem == 1) {
            listOfUsers = Database.getUsersByAdress(tfSearch.getText());
        } else if (selectedItem == 2) {
            listOfUsers = Database.getUsersByPhone(tfSearch.getText());
        }
        Database.shutdown();

        //populating SearchList with results
        if (listOfUsers != null) {
            userList.setModel(new SearchListPopulate(listOfUsers));
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        userList = new javax.swing.JList();
        tfSearch = new javax.swing.JTextField();
        cbSelection = new javax.swing.JComboBox();
        btnSearch = new javax.swing.JButton();
        btnSave = new javax.swing.JButton();
        btnEdit = new javax.swing.JButton();
        btnDeleteUser = new javax.swing.JButton();
        btnAddUser = new javax.swing.JButton();
        userInfoPanel = new employ.UserInfoPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jScrollPane1.setViewportView(userList);

        cbSelection.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Name", "Phone", "Address" }));

        btnSearch.setText("Search");

        btnSave.setText("Save");

        btnEdit.setText("Edit");

        btnDeleteUser.setText("Delete user");

        btnAddUser.setText("Add new user");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 410, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(tfSearch)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cbSelection, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSearch)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnAddUser)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnEdit, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSave)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnDeleteUser))
                    .addComponent(userInfoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 469, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cbSelection, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnSearch)
                    .addComponent(btnSave)
                    .addComponent(btnEdit)
                    .addComponent(btnDeleteUser)
                    .addComponent(btnAddUser))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addComponent(userInfoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 392, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAddUser;
    private javax.swing.JButton btnDeleteUser;
    private javax.swing.JButton btnEdit;
    private javax.swing.JButton btnSave;
    private javax.swing.JButton btnSearch;
    private javax.swing.JComboBox cbSelection;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField tfSearch;
    private employ.UserInfoPanel userInfoPanel;
    private javax.swing.JList userList;
    // End of variables declaration//GEN-END:variables
}
